﻿using ExcelConfig;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;
using wx_api.net.Dto;

namespace wx_api.net
{
    public class WxAPI
    {
        const string api_host = "https://api.weixin.qq.com";
        public static async Task<ReadTokenOutput> ReadToken(string appid, string secret)
        {
            var client = new TouchSocket.Http.HttpClient();
            var config = new TouchSocketConfig();
            config.SetRemoteIPHost(new IPHost(api_host));
            await client.SetupAsync(config);
            await client.ConnectAsync();
            var request = new HttpRequest();
            request.InitHeaders()
                .SetUrl($"/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}")
                .SetHost(api_host)
                .AsGet();

            using (var responseResult = await client.RequestAsync(request, 1000 * 10))
            {
                var response = responseResult.Response;
                var content = await response.GetDataAsync<ReadTokenOutput>();
                return content;
            }
        }

        public static async Task<ReadTicketOutput> ReadTicket(string token)
        {
            var client = new TouchSocket.Http.HttpClient();
            var config = new TouchSocketConfig();
            config.SetRemoteIPHost(new IPHost(api_host));
            await client.SetupAsync(config);
            await client.ConnectAsync();
            var request = new HttpRequest();
            request.InitHeaders()
                .SetUrl($"/cgi-bin/ticket/getticket?access_token={token}&type=jsapi")
                .SetHost(api_host)
                .AsGet();

            using (var responseResult = await client.RequestAsync(request, 1000 * 10))
            {
                var response = responseResult.Response;
                var content = await response.GetDataAsync<ReadTicketOutput>();
                return content;
            }

        }
    }
}
